package com.open.capacity.user.controller;

import com.alibaba.druid.sql.visitor.functions.Char;
import com.open.capacity.common.exception.controller.ControllerException;
import com.open.capacity.common.exception.service.ServiceException;
import com.open.capacity.common.model.SysResume;
import com.open.capacity.common.web.PageResult;
import com.open.capacity.common.web.Result;
import com.open.capacity.log.annotation.LogAnnotation;
import com.open.capacity.user.model.FileInfo;
import com.open.capacity.user.service.FeignService;
import com.open.capacity.user.service.SysResumeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@Api(tags = "USER API")
public class SysResumeController {
    @Autowired
    private SysResumeService sysResumeService;

    @Autowired
    private FeignService feignService;

    @Value("${files.resume.up_file}")
    private String resumePath;

    /**
    * @Description: 添加简历信息
    * @Param: [sysResume]
    * @return: com.open.capacity.common.web.Result
    * @Author: bellweather
    * @Date: 2021/1/9
    */
    @PutMapping("/resume")
    public Result saveResume(@RequestBody SysResume sysResume){
        int save = sysResumeService.save(sysResume);
        return Result.succeed(save==1?"保存成功!":"保存失败");
    }

    /*/**
    * @Description: 按条件查找简历信息
    * @Param: [params]
    * @return: com.open.capacity.common.web.PageResult<com.open.capacity.common.model.SysResume>
    * @Author: bellweather
    * @Date: 2021/1/9
    */
    @GetMapping("/resumes")
    public PageResult<SysResume> getResumeList(@RequestParam Map<String,Object> params){
        return sysResumeService.findList(params);
    }

    @DeleteMapping("/resume/{id}")
    public Result deleteResule(@PathVariable("id") int id){
        int i = sysResumeService.deleteByPrimaryKey((long) id);
        return Result.succeed(i>0?"删除成功":"删除失败");
    }

    /**
    * @Description: 修改简历信息
    * @Param: [sysResume]
    * @return: com.open.capacity.common.web.Result
    * @Author: bellweather
    * @Date: 2021/1/9
    */
    @PostMapping("/resume")
    public Result updateaResume(@RequestBody SysResume sysResume){
        int i = sysResumeService.updateByPrimaryKey(sysResume);
        return Result.succeed(i==1?"修改成功!":"修改失败");

    }
    /**
    * @Description: 上传文件到 ${resumePath}路径下
    * @Param: [file] 文件
    * @return: com.open.capacity.common.web.Result    返回字符串
    * @Author: bellweather
    * @Date: 2021/1/9
    */
    @PostMapping("/resume/upload")
    @CrossOrigin
    public Result uploadResume(@RequestParam("file") MultipartFile file,
                               @RequestParam("name") String name,
                               @RequestParam("userId")int userId) {
        String originalFilename = file.getOriginalFilename();
        String sub=originalFilename.substring(originalFilename.lastIndexOf("."));

        String subfix="\\"+LocalDate.now().toString().replace("-","\\")+"\\";

        if(!StringUtils.isBlank(name))
            subfix+=name+sub;
        else
            subfix+=originalFilename;

        String realPath = resumePath+subfix;
        File newFile = new File(realPath);
        if (!newFile.exists()) {
            try {
                newFile.createNewFile();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), newFile);
        } catch (IOException e) {
//            e.printStackTrace();
            return Result.failedWith(null,500,"错误"+e.getCause());
        }
        return Result.failedWith(realPath,200,"操作成功！");
    }

    /**
    * @Description: 调用file-center上传文件
    * @Param: [file] 文件
    * @return: com.open.capacity.user.model.FileInfo  返回文件信息
    * @Author: bellweather
    * @Date: 2021/1/9
     */
    @CrossOrigin
    @PostMapping("/resume/file/upload")
    public FileInfo updalod(@RequestPart("file")MultipartFile file){
        FileInfo updload = feignService.updload(file);
        return updload;
    }


    /*/**
    * @Description:
    * @Param: [id  简历Id, response 响应]
    * @return: void
    * @Author: bellweather
    * @Date: 2021/1/11
    */
    @GetMapping("resume/download")
    public void downLoadResume(@RequestParam("id") String id, HttpServletResponse response) throws IOException {
        SysResume byId = sysResumeService.findById(id);
        String path =byId.getUri();
        String subfix=path.substring(path.lastIndexOf(".")+1);
        String fileName =path.substring(path.lastIndexOf("\\")+1);
        ServletOutputStream out = null;
        InputStream source = null;
        InputStream in = null;
        try {
            byte[] buffer =new byte[1024];
            int len=0;
            source = new FileInputStream(new File(path));
            String resouceStr = inputStream2String(source);
            byte[] bytes = Base64.decodeBase64(resouceStr);
            in=new ByteArrayInputStream(bytes);

            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));
            out = response.getOutputStream();
            while ((len=in.read(buffer))!=-1){
                out.write(buffer,0,len);
            }


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(in!=null)
                in.close();
            if(out!=null)
                out.close();
        }
    }

    public String inputStream2String(InputStream in) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int len = 0;
        byte[] b = new byte[1024];
        while ((len = in.read(b, 0, b.length)) != -1) {
            baos.write(b, 0, len);
        }
        byte[] buffer =  baos.toByteArray();
        //base64加密
        return Base64.encodeBase64String(buffer);
    }
}
